package com.example.demo.service;

import com.example.demo.main.ShowCart;
import com.example.demo.main.User;
import com.example.demo.main.UserCart;
import com.example.demo.main.UserExample;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.Imp.SelectAllOfSQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class UserService implements SelectAllOfSQL {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserExample userExample;
    @Autowired
    private UseSQLByCart useSQLByCart;

    public int toRegister(User user) {

        return userMapper.insertSelective(user);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    public boolean updateByName(String val, String str, String name) {
        User user = new User();
        user.setUserName(name);
        switch (str) {
            case "email":
                user.setUserEmail(val);
                break;
            case "phone":
                user.setUserPhone(val);
                break;
            case "school":
                user.setUserSchool(val);
                break;
            case "major":
                user.setUserMajor(val);
        }
        return userMapper.updateByPrimaryKeySelective(user) > 0;
    }

    /**
     * 检查用户名和密码
     *
     * @param name
     * @param pwd
     * @return
     */
    public boolean checkNamePWd(String name, String pwd) {
        userExample.clear();
        userExample.or().andUserNameEqualTo(name).andUserPwdEqualTo(pwd);
        return userMapper.selectByExample(userExample).size() > 0;
    }

    public ShowCart showCartPriceAndCount(String userName) {
        List<UserCart> userCartList = useSQLByCart.selectByUserName(userName);
        BigDecimal price = new BigDecimal("0");
        Integer count = 0;
        for (UserCart userCart : userCartList
        ) {
            price = price.add(userCart.getPrice());
            price = price.multiply(BigDecimal.valueOf(userCart.getCount()));
            count += userCart.getCount();
        }

        return new ShowCart(price, count);
    }
}

